package com.ttxs.common.security.aspect;

import com.ttxs.common.core.constant.SecurityConstant;
import com.ttxs.common.core.redis.RedisService;
import com.ttxs.common.core.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * 限制请求绕过网关，直接访问服务
 */
@Slf4j
@Aspect
public class RequestMappingAspect {
    @Autowired
    private RedisService redisService;

    public static final String POINT_SIGN = "@annotation(org.springframework.web.bind.annotation.RequestMapping) || "
            + "@annotation(org.springframework.web.bind.annotation.GetMapping) || "
            + "@annotation(org.springframework.web.bind.annotation.PostMapping) || "
            + "@annotation(org.springframework.web.bind.annotation.PutMapping) || "
            + "@annotation(org.springframework.web.bind.annotation.DeleteMapping)";

    public RequestMappingAspect() {
        log.warn("ttxs.security.secretKeyEnabled配置开启，只能通过网关访问本系统");
    }

    @Pointcut(value = POINT_SIGN)
    public void pointcut() {}

    @Before(value = "pointcut()")
    public void before(JoinPoint joinPoint) {
        verifySecretKey(joinPoint);
    }

    private void verifySecretKey(JoinPoint joinPoint) {
        String secretKey = ServletUtils.getRequest().getHeader(SecurityConstant.SECRET_KEY);
        String key = (String) redisService.get(SecurityConstant.SECRET_KEY);
        if (log.isDebugEnabled()) {
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
            log.debug("验证安全key:{},{}",secretKey, key);
            log.debug("映射请求类型：{}", Arrays.toString(declaredAnnotations));
            log.debug("映射类.方法：{}", joinPoint.getTarget().getClass() + "." + joinPoint.getSignature().getName());
        }
        if(!StringUtils.hasText(secretKey)) {
            throw new IllegalStateException("安全key丢失，禁止访问");
        }
        if(!key.equals(secretKey)) {
            throw new IllegalStateException("安全key不匹配，禁止访问");
        }
    }

}
